/*
 * File: javaScriptServlet.java Author: Robert Bittle <guywithnose@gmail.com>
 */
package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import data.FileReader;
import data.Memcache;
import fileHandlers.JavaScriptMinifier;

/**
 * The Class javaScriptServlet.
 * 
 * @author Dude
 */
public class JavaScriptServlet extends FoxtrotBravoServlet
{
  /*
   * (non-Javadoc)
   * 
   * @see
   * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
   * , javax.servlet.http.HttpServletResponse)
   */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException
  {
    resp.setHeader("Content-Type", "application/javascript");
    String files = req.getParameter("files");
    if (files != null)
    {
      String[] arFiles = files.split(",");
      for (int i = 0; i < arFiles.length; i++)
      {
        String fileName;
        fileName = "js/" + arFiles[i];
        if (BrowserCache.handleCache(req, resp, 3600/* 1 hour */, fileName))
        {
          return;
        }
        String Contents = null;
        if (isDevMode(req))
        {
          Memcache.clear();
          Contents = FileReader.getFileContents(fileName);
        } else
        {
          Contents = getMinifiedJs(fileName);
        }
        resp.getWriter().println(Contents);
      }
    }
  }

  /**
   * Get Minified js.
   * 
   * @param fileName
   *          the file name
   * @return the minified js
   */
  private static String getMinifiedJs(String fileName)
  {
    String Contents = Memcache.get("JSFILE" + fileName);
    if (Contents == null)
    {
      if ((Contents = FileReader.getFileContents(fileName.replace(".js",
          ".min.js"))) == null)
      {
        Contents = JavaScriptMinifier.minify(fileName);
      }
      Memcache.set("JSFILE" + fileName, Contents);
    }
    return Contents;
  }
  
}
